package models

import (
	"errors"
	"github.com/jinzhu/gorm"
)

type Role struct {
	ID       int    	`json:"role_id"`
	RoleName string `json:"role_name"`
}

func RoleInsert(r Role) error {
	err := db.Create(&r).Error

	if err != nil {
		return err
	}

	return nil
}


// Selects 返回所有角色列表
func RoleSelects() ([]*Role, error){
	var (
		r []*Role
		rs []*Role
	)

	err := db.Find(&rs).Error
	if err != gorm.ErrRecordNotFound && err != nil {
		return nil, err
	}


	for _, v := range rs {
		r = append(r, v)
	}

	return r, nil
}

// GetDeptNameById 根据角色Id返回角色名称
func GetRoleNameById(roleId int) (*Role, error){
	var r Role
	err := db.Where("id = ?", roleId).Find(&r).Error
	if err != gorm.ErrRecordNotFound && err != nil {
		return nil, err
	}

	if r.ID > 0 {
		return &r, nil
	}

	return nil, errors.New("未知错误")
}

func CheckRoleIsExisted(roleName string) bool {
	var r Role
	err := db.Where("role_name = ?", roleName).Find(&r).Error

	if err == gorm.ErrRecordNotFound {
		return false
	}

	return true
}